<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class OrderInvoice extends Model
{
    protected $table = "c_order_invoices";

    public function order()
    {
        return $this->belongsTo('App\Models\Order', 'order_id');
    }
    /***
     * @param $data
     * @return bool
     * 申请发票
     */
    public function addInvoice($data)
    {
        $order = (new Order())->where([['id', '=', $data['order_id']]])->first();//value("is_invoice");
        if ($order->is_invoice == 1) {
            return "您已经申请过发票,不能重复申请!";
        }
        try {
            DB::beginTransaction(); // 开始事务
            $this->order_id = isset($data['order_id']) ? $data['order_id'] : "";
            $this->type = isset($data['type']) ? $data['type'] : 1;
            $this->content = isset($data['content']) ? $data['content'] : "";
            $this->head_type = isset($data['head_type']) ? $data['head_type'] : "";
            $this->head_name = isset($data['head_name']) ? $data['head_name'] : "";
            $this->head_num = isset($data['head_num']) ? $data['head_num'] : "";
            $this->name = isset($data['name']) ? $data['name'] : "";
            $this->phone = isset($data['phone']) ? $data['phone'] : "";
            $this->province_id = isset($data['province_id']) ? $data['province_id'] : "";
            $this->city_id = isset($data['city_id']) ? $data['city_id'] : "";
            $this->district_id = isset($data['county_id']) ? $data['county_id'] : "";
            $this->address = isset($data['address']) ? $data['address'] : "";
            $this->register_address = isset($data['register_address']) ? $data['register_address'] : "";
            $this->register_phone = isset($data['register_phone']) ? $data['register_phone'] : "";
            $this->open_bank = isset($data['open_bank']) ? $data['open_bank'] : "";
            $this->bank_num = isset($data['bank_num']) ? $data['bank_num'] : "";
            $this->order_source = $order->order_source;
            $this->work_id = $order->work_id;
            $this->suppliers_id = $order->suppliers_id;
            $res = $this->save();
            if ($res) {
                $dd = (new Order())->where([['id', '=', $data['order_id']]])->update(['is_invoice' => 1]);
                if ($dd) {
                    DB::commit(); // 提交事务
                    return true;
                }
            }
            DB::rollback(); // 回滚事务
        } catch (Exception $e) {
            DB::rollback(); // 回滚事务
        }
    }

    /**
     * @param $id
     * @return mixed
     * 获取地址名称
     */
    public function getChinAddress($id)
    {
        return (new Area())->getNameById($id);
    }
}
